import express from 'express';
import {
  getQuestionsByKnowledge,
  generateQuestion,
  getQuestionDetail
} from '../controllers/questionController';
import questionService from '../services/questionService';
import { generateAdditionAssociative, getSolution } from '../services/question-generators/arithmetic-laws/addition-associative';

const router = express.Router();

// 按知识点获取题目
router.get('/', getQuestionsByKnowledge);

// 自动生成题目
router.post('/generate', generateQuestion);

// 获取题目详情
router.get('/:id', getQuestionDetail);

router.post('/generate/addition-associative', async (req, res) => {
  try {
    const difficulty = req.body.difficulty || 1;
    const knowledgeCode = 'arithmetic-laws-addition-associative';
    
    const generatedQuestion = generateAdditionAssociative(difficulty);
    
    // 实时生成题目不持久化
    const generatedAt = new Date().toISOString();
    
    res.json({
      question: `${generatedQuestion.content} = ____`,
      answer: generatedQuestion.solution.split('=').pop()?.trim() ?? '',
      difficulty: generatedQuestion.difficulty,
      generatedAt
    });
    
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: '生成题目失败' });
  }
});

export default router;
